import React from 'react'
import BraftEditor from 'braft-editor'
import {ContentUtils} from 'braft-utils'
import {Upload, Icon} from 'antd'
import 'braft-editor/dist/index.css'
import styles from './index.less'
import {qiniuConfig} from "../../config/config";
import {beforeUpload} from "../../utils/utils";

export default class DraftEditor extends React.PureComponent {

  constructor(props) {
    super(props);

    this.state = {
      loading: false,
    };
  }

  handleChange = ({file}) => {
    const {status, response = {}} = file;
    if (status === 'done') {
      const {value, onChange} = this.props;
      const newValue = ContentUtils.insertMedias(value, [{
        type: 'IMAGE',
        url: qiniuConfig.baseExternalLink + (response.hash || ''),
      }]);
      onChange(newValue);

      this.setState({
        loading: false,
      });
    } else if (status === 'uploading') {
      this.setState({
        loading: true,
      });
    }
  };

  render() {
    const {loading} = this.state;
    const excludeControls = ['media'];
    const extendControls = [
      {
        key: 'antd-uploader',
        type: 'component',
        component: (
          <Upload
            accept="image/*"
            showUploadList={false}
            action={`${qiniuConfig.server}`}
            data={{token: qiniuConfig.token}}
            beforeUpload={beforeUpload}
            onChange={this.handleChange}
          >
            <button type="button" className="control-item button upload-button" data-title="插入图片">
              {
                loading
                  ? <Icon type="loading" />
                  : <Icon type="picture" theme="filled"/>
              }
            </button>
          </Upload>
        )
      }
    ];

    return (
      <BraftEditor
        className={styles.kEditor}
        excludeControls={excludeControls}
        extendControls={extendControls}
        {...this.props}
      />
    )
  }
}
